import { _decorator, Component, Node, Label, tween, view, UITransform, Vec3, SpriteAtlas, SpriteFrame, Sprite, Button, ScrollView, EditBox, EventTouch, find } from 'cc';
import { App } from '../App';
import { EventConst } from '../common/Common';
import { authorize, play } from '../common/web3';
import CommConst from '../const/CommConst';
import wsTool from '../net/ws';
import { PD } from '../player/PlayerData';
import { LoadMg } from '../tools/LoadMg';
import { setLanguagePopuUp, showTip } from '../tools/PopuUp';
import { TipMg } from '../tools/TipMg';
import UtilTool from '../tools/UtilTool';
import { WalletPanel } from './WalletPanel';
const { ccclass, property } = _decorator;

// 金币购买、兑换界面
@ccclass('WalletSwapPanel')
export class WalletSwapPanel extends Component {
    @property(Node)
    contentNode: Node = null;

    @property(Node)
    recharge_bg: Node = null;

    @property(Node)
    exchange_bg: Node = null;

    @property(Node)
    coin1: Node = null;

    @property(Node)
    coin2: Node = null;

    private parentObj:WalletPanel = null
    private viewIndex = 0 //界面索引 [0]购买界面 [1]兑换界面
    private re_coinNum = 0 // 购买金币数量
    private wi_coinNum = 0 // 兑换金币数量

    private gm_USDTLabel = null // 购买需要的U
    private dh_USDTLabel = null // 兑换需要的U
    private min_re = PD.gameConfig.chargeMinLimit // 最小购买对应U的数额
    private min_wi = PD.gameConfig.withdrawMinLimit // 最小兑换对应U的数额

    onLoad() {
        App.Event.on(EventConst.UPDATE_COIN,this.setCoin, this )

        this.node.getComponent(UITransform).setContentSize(view.getVisibleSize())
        UtilTool.setScreen(this.node)

        App.onClick.addButtonClickEvent(this.recharge_bg.getChildByName("btn_recharge").getComponent(Button), async() =>{
            this.gotoRecharge()
        }, this,null,true,null,null,1000); 
        App.onClick.addButtonClickEvent(this.exchange_bg.getChildByName("btn_exchange").getComponent(Button), async() =>{
            this.gotoExchange()
        }, this,null,true,null,null,1000); 
    }

    start() {
        this.setCoin()
    }

    /**
     * 选择界面
     */
    showView(obj,index) {
        this.parentObj = obj
        this.viewIndex = index
        this.recharge_bg.active = index==0
        this.exchange_bg.active = index==1

        UtilTool.nodeActive(this.contentNode,5,0.16)

        this.gm_USDTLabel = find("editboxBg/needUSDT",this.recharge_bg)
        this.dh_USDTLabel = find("editboxBg/needUSDT",this.exchange_bg)

        if (this.viewIndex==0) {
            // 初始化购买界面
            // 输入框
            let coinEditBox = this.recharge_bg.getChildByName("editboxBg").getChildByName("coinEditBox").getComponent(EditBox)
            coinEditBox.inputMode = EditBox.InputMode.NUMERIC;
            coinEditBox.node.on('text-changed',(e)=>{
                coinEditBox.string = UtilTool.getNumberStr(e.string)
                coinEditBox.string = Math.floor(e.string) + ""
                this.re_coinNum = parseInt(coinEditBox.string);
                this.setUSDT(0)
                UtilTool.printLog(this.re_coinNum,e.string,'num');
            })

            coinEditBox.node.on('editing-did-ended',(e)=>{
                coinEditBox.string = Math.floor(e.string) + ""
                this.re_coinNum = parseInt(coinEditBox.string);
                this.setUSDT(0)
                UtilTool.printLog(this.re_coinNum,e.string,'num');
            })
            this.setUSDT(0)

        }
        else {
            // 初始化兑换界面
            // 输入框
            let coinEditBox = this.exchange_bg.getChildByName("editboxBg").getChildByName("coinEditBox").getComponent(EditBox)
            coinEditBox.inputMode = EditBox.InputMode.NUMERIC;
            coinEditBox.node.on('text-changed',(e)=>{
                coinEditBox.string = UtilTool.getNumberStr(e.string)
                coinEditBox.string = Math.floor(e.string) + ""
                this.wi_coinNum = parseInt(coinEditBox.string);
                this.setUSDT(1)
                UtilTool.printLog(this.wi_coinNum,e.string,'num');
            })

            coinEditBox.node.on('editing-did-ended',(e)=>{
                coinEditBox.string = Math.floor(e.string) + ""
                this.wi_coinNum = parseInt(coinEditBox.string);
                this.setUSDT(1)
                UtilTool.printLog(this.wi_coinNum,e.string,'num');
            })
            this.setUSDT(1)
        }

        // 测试
        this.setRechargeTip(PD.gameConfig.chargeScale, this.min_re)
        this.setExchangeeTip(1/PD.gameConfig.chargeScale, this.min_wi)
    }

    /**
     * 更新金币
     */
    setCoin() {
        var coin = PD.user.coin.toString()

        if (this.viewIndex==0) {
            this.coin1.getComponent(Label).string = App.language.getLanguageLab(69) + coin
        }
        else{
            this.coin2.getComponent(Label).string = App.language.getLanguageLab(69) + coin
        }
    }

    /**
     * 更新U的值
     */
    setUSDT(type) {
        if (type==0) {
            this.gm_USDTLabel.getComponent(Label).string = "" + this.re_coinNum/PD.gameConfig.chargeScale + " " + PD.user.usdt
        }
        else{
            this.dh_USDTLabel.getComponent(Label).string = "" + this.wi_coinNum/PD.gameConfig.chargeScale + " " + PD.user.usdt
        }
    }

    /**
     * 关闭
     */
    clickClose() {
        App.Audio.playOneShot("click")
        this.node.destroy()
    }

    ////////////////////////////////////////////////////////////////////////////////////// 购买界面 //////////////////////////////////////////////////////////////////////////////////////

    /**
     * 购买
     */
    async gotoRecharge() {
        let that = this
        App.Audio.playOneShot("click")
        UtilTool.printLog("点击购买")

        if (this.re_coinNum==-1 || this.re_coinNum==0) {
            showTip(App.language.getLanguageLab(73))
            return
        }

        if (this.re_coinNum/PD.gameConfig.chargeScale < this.min_re) {
            showTip(App.language.getLanguageLab(70) + this.min_re + PD.user.usdt)
            return
        }

        try {
            
            // 获取订单id
            let orderInfo = await wsTool.send({ "msgCode": CommConst.Req_CZORDER, "type": 1 /* goodsId.BackEndGoodsId */ });
            LoadMg.showLoad({type:1,content:App.language.getLanguageLab(75)})
            //调取授权
            let authorizeInfo = await authorize(null,this.re_coinNum, this.re_coinNum/PD.gameConfig.chargeScale);
            let playInfo = await play(orderInfo.orderNo)
            UtilTool.printLog(orderInfo, '订单信息');
            UtilTool.printLog(authorizeInfo, '授权信息');
            UtilTool.printLog(playInfo, '购买信息');
            if (playInfo) {
                LoadMg.removeLoad()
                showTip(App.language.getLanguageLab(59))
                wsTool.send({ "msgCode": CommConst.Req_CZORDER_CB, "orderNo": orderInfo.orderNo, "blockHash":playInfo.blockHash})
                .then(res =>{
                    if (that.parentObj) {
                        that.parentObj.resetReqdata(false,0)
                    }
                    if (that.node) {
                        that.node.destroy()
                    }
                })
                
            } else {
                showTip(App.language.getLanguageLab(60))
                LoadMg.removeLoad()
            }
        } catch (error) {
            showTip(App.language.getLanguageLab(60))
            UtilTool.printLog('usdt购买失败', error);
            LoadMg.removeLoad()

        }
    }

    /**
     * tip
     */
    setRechargeTip(value1,value2) {
        this.recharge_bg.getChildByName("tip1").getComponent(Label).string = "*1" + " " + PD.user.usdt + App.language.getLanguageLab(76) + value1 + App.language.getLanguageLab(58)
        this.recharge_bg.getChildByName("tip2").getComponent(Label).string = "*" + App.language.getLanguageLab(70) + value2 + " " + PD.user.usdt

        this.recharge_bg.getChildByName("tip1").getComponent(Label).fontSize = App.language.languageId_default==App.language.language_EnglishId?38:42
        this.recharge_bg.getChildByName("tip2").getComponent(Label).fontSize = App.language.languageId_default==App.language.language_EnglishId?38:42
    }





    ////////////////////////////////////////////////////////////////////////////////////// 兑换界面 //////////////////////////////////////////////////////////////////////////////////////

    /**
     * 兑换
     */
    gotoExchange() {
        App.Audio.playOneShot("click")
        UtilTool.printLog("点击兑换")

        if (this.wi_coinNum==-1 || this.wi_coinNum==0) {
            showTip(App.language.getLanguageLab(73))
            return
        }

        if (this.wi_coinNum/PD.gameConfig.chargeScale < this.min_wi) {
            showTip(App.language.getLanguageLab(72) + this.min_wi + PD.user.usdt)
            return
        }

        if (this.wi_coinNum > PD.user.coin) {
            showTip(App.language.getLanguageLab(77))
            return
        }

        wsTool.send({"msgCode":CommConst.Req_EXCHANGEAL, "usdt":Math.floor(this.wi_coinNum)}) // usdt这个传参是代表金币数值
        .then(res =>{
            // if (res?.result == 0) {
                showTip(App.language.getLanguageLab(64))
                if (this.parentObj) {
                    this.parentObj.resetReqdata(false,1)
                }
                if (this.node) {
                    this.node.destroy()
                }
                
            // }
            // else{
            //     alert('获取数据失败')
            // } 
        })

    }

    /**
     * tip
     */
    setExchangeeTip(value1,value2) {
        this.exchange_bg.getChildByName("tip1").getComponent(Label).string = "*1" + App.language.getLanguageLab(58) + App.language.getLanguageLab(71) + value1 + " " + PD.user.usdt
        this.exchange_bg.getChildByName("tip2").getComponent(Label).string = "*" + App.language.getLanguageLab(72) + value2 + " " + PD.user.usdt

        this.exchange_bg.getChildByName("tip1").getComponent(Label).fontSize = App.language.languageId_default==App.language.language_EnglishId?38:42
        this.exchange_bg.getChildByName("tip2").getComponent(Label).fontSize = App.language.languageId_default==App.language.language_EnglishId?38:42
    }

    onDestroy() {
        App.Event.off(EventConst.UPDATE_COIN,this.setCoin,this)
    }

}

